<template>
  <div class="header">
    <div class="header-content">
      <div class="left-section">
        <h1>亿达电影</h1>
        <div class="city-selector" @click="toggleCityPanel">
          <i class="iconfont icon-location"></i>
          <span class="city-name">{{ locationInfo || '定位中...' }}</span>
          <i class="arrow-down" :class="{ 'arrow-up': showCityPanel }"></i>

          <div class="location-tip" v-if="locationInfo">
            当前定位城市：{{ locationInfo }}
          </div>

          <div class="city-panel" v-show="showCityPanel">
            <div class="current-city">
              <div class="section-title">当前定位城市</div>
              <div class="current-city-name" @click="backToActualLocation">
                <i class="iconfont icon-location"></i>
                {{ actualLocationCity || '定位中...' }}
                <span class="back-tip" v-if="locationInfo !== actualLocationCity">
                  (点击返回定位城市)
                </span>
              </div>
            </div>

            <div class="city-list">
              <div class="city-group" v-for="(cityGroup, letter) in groupedCities" :key="letter">
                <div class="letter">{{ letter }}</div>
                <div class="cities">
                  <div class="city-item"
                       v-for="city in cityGroup"
                       :key="city.adcode"
                       @click="selectCity(city)">
                    {{ city.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="center-section">
        <div class="top-nav">
          <router-link to="/" class="nav-link" :class="{ active: $route.path === '/' }">首页</router-link>
          <router-link to="/films" class="nav-link" :class="{ active: $route.path === '/films' }">电影</router-link>
          <router-link to="/cinemas" class="nav-link" :class="{ active: $route.path === '/cinemas' || $route.path === '/cinema' }">影院</router-link>
        </div>
      </div>

      <div class="right-section">
        <div class="user-actions" v-if="!userInfo">
          <button class="btn-login" @click="$router.push('/login')">登录</button>
        </div>
        <div class="user-profile" v-else @click="toggleUserMenu">
          <div class="avatar">
            <img :src="userInfo.avatar || 'https://api.dicebear.com/7.x/avataaars/svg?seed=default'" alt="用户头像">
          </div>
          <div class="user-menu" v-show="showUserMenu">
            <div class="menu-item" @click="handleProfileClick">
              <i class="iconfont icon-user"></i>
              个人信息
            </div>
            
            <div class="menu-divider"></div>
            <div class="menu-item" @click="handleLogout">
              <i class="iconfont icon-logout"></i>
              退出登录
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, inject, computed } from 'vue'
import { useRouter } from 'vue-router'
import { pinyin } from 'pinyin-pro'

const locationInfo = inject('locationInfo', ref(null))
const updateLocation = inject('updateLocation', (city) => {
  console.error('updateLocation 未正确提供，使用默认实现')
  locationInfo.value = city
})
const showCityPanel = ref(false)
const AMap = ref(null)
const cities = ref([])
const router = useRouter()
const userInfo = ref(null)
const showUserMenu = ref(false)
const actualLocationCity = ref(null)

// 初始化高德地图
const initAMap = () => {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      AMap.value = window.AMap
      resolve(window.AMap)
      return
    }

    window.initAMapCallback = () => {
      AMap.value = window.AMap
      resolve(window.AMap)
    }

    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `https://webapi.amap.com/maps?v=2.0&key=57767578b7f25b7c37380e11b5e55ff7&plugin=AMap.Geolocation&callback=initAMapCallback`
    script.onerror = () => reject(new Error('高德地图加载失败'))
    document.head.appendChild(script)
  })
}

// 获取城市列表
const fetchCities = async (retryCount = 3) => {
  for (let i = 0; i < retryCount; i++) {
    try {
      console.log('开始获取城市列表...')
      const response = await fetch('https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=2&key=57767578b7f25b7c37380e11b5e55ff7')
      const data = await response.json()
      console.log('获取到的原始数据:', data)

      if (data.status === '1') {
        if (!data.districts || !data.districts[0] || !data.districts[0].districts) {
          throw new Error('城市数据结构不正确')
        }

        // 处理城市数据，添加拼音首字母
        const cityList = data.districts[0].districts.reduce((acc, province) => {
          if (!province.districts) return acc

          const provinceCities = province.districts.map(city => {
            // 获取城市名称的拼音首字母（大写）
            const pinyinLetter = pinyin(city.name, { pattern: 'first', toneType: 'none' }).charAt(0).toUpperCase()
            return {
              name: city.name,
              letter: pinyinLetter,
              adcode: city.adcode
            }
          })
          return [...acc, ...provinceCities]
        }, [])

        console.log('处理后的城市列表:', cityList)
        cities.value = cityList.sort((a, b) => a.letter.localeCompare(b.letter))
        console.log('最终排序后的城市列表:', cities.value)
        return
      }
      throw new Error('获取城市列表失败')
    } catch (error) {
      console.error(`获取城市列表失败 (尝试 ${i + 1}/${retryCount}):`, error)
      if (i === retryCount - 1) {
        // 最后一次尝试失败，设置默认城市列表（已包含拼音首字母）
        cities.value = [
          { name: '北京市', letter: 'B', adcode: '110100' },
          { name: '上海市', letter: 'S', adcode: '310100' },
          { name: '广州市', letter: 'G', adcode: '440100' },
          { name: '深圳市', letter: 'S', adcode: '440300' },
          { name: '杭州市', letter: 'H', adcode: '330100' },
          { name: '南京市', letter: 'N', adcode: '320100' },
          { name: '成都市', letter: 'C', adcode: '510100' },
          { name: '武汉市', letter: 'W', adcode: '420100' },
          { name: '西安市', letter: 'X', adcode: '610100' },
          { name: '重庆市', letter: 'C', adcode: '500100' },
          { name: '天津市', letter: 'T', adcode: '120100' },
          { name: '苏州市', letter: 'S', adcode: '320500' },
          { name: '青岛市', letter: 'Q', adcode: '370200' },
          { name: '大连市', letter: 'D', adcode: '210200' },
          { name: '厦门市', letter: 'X', adcode: '350200' }
        ]
        console.log('默认城市列表已设置:', cities.value)
      }
    }
  }
}

// 获取当前位置
const getLocation = async () => {
  try {
    console.log('开始获取位置信息...')
    
    // 如果已经有选择的城市，直接返回
    if (locationInfo.value) {
      console.log('保持用户已选择的城市:', locationInfo.value)
      return
    }

    // 检查本地存储中的城市选择
    const savedCity = localStorage.getItem('selectedCity')
    const savedTimestamp = localStorage.getItem('cityTimestamp')
    
    if (savedCity && savedTimestamp && (Date.now() - Number(savedTimestamp)) < 24 * 60 * 60 * 1000) {
      console.log('使用已保存的城市选择:', savedCity)
      updateLocation(savedCity)
      return
    }

    // 如果没有选��的城市，才进行 IP 定位
    const response = await fetch('https://restapi.amap.com/v3/ip?key=57767578b7f25b7c37380e11b5e55ff7')
    const data = await response.json()

    if (data.status === '1' && data.city) {
      updateLocation(data.city)
      updateActualLocation(data.city)
      // 保存实际定位城市，但不作为选择的城市
      localStorage.setItem('actualLocationCity', data.city)
      return
    }

    throw new Error('IP 定位失败')

  } catch (error) {
    console.error('定位失败:', error)
    if (!locationInfo.value) {
      updateLocation('北京')
      updateActualLocation('北京')
    }
  }
}

// 选择城市
const selectCity = (city) => {
  updateLocation(city.name)
  // 保存用户选择的城市
  localStorage.setItem('selectedCity', city.name)
  localStorage.setItem('cityTimestamp', Date.now().toString())
  showCityPanel.value = false
}

// 组件挂载时初始化
onMounted(async () => {
  console.log('AppHeader 组件挂载')
  await getLocation()
  await fetchCities()

  // 初始化实际定位城市
  const actualCity = localStorage.getItem('actualLocationCity')
  if (actualCity) {
    updateActualLocation(actualCity)
  }
  checkLoginStatus()
  document.addEventListener('click', closeUserMenu)
})

onUnmounted(() => {
  document.removeEventListener('click', closeUserMenu)
})

// 检查用户登录状态
const checkLoginStatus = () => {
  try {
    const userData = localStorage.getItem('user')
    console.log('当前用户数据:', userData)  // 调试日志

    if (userData) {
      userInfo.value = JSON.parse(userData)
      console.log('解析后的用户信息:', userInfo.value)  // 调试日志
    } else {
      console.log('未找到用户数据')  // 调试日志
      userInfo.value = null
    }
  } catch (error) {
    console.error('解析用户数据出错:', error)
    userInfo.value = null
  }
}

// 切换用户菜单显示状态
const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('user')
  localStorage.removeItem('token')  // 确保也清除 token
  userInfo.value = null
  showUserMenu.value = false
  router.push('/login')
}

// 点击其他地方关闭用户菜单
const closeUserMenu = (e) => {
  if (!e.target.closest('.user-profile')) {
    showUserMenu.value = false
  }
}

// 处理个人信息点击
const handleProfileClick = () => {
  showUserMenu.value = false
  router.push('/profile')
}

// 添加城市分组的计算属性
const groupedCities = computed(() => {
  console.log('正在处理城市分组，当前城市列表:', cities.value)
  const groups = {}
  cities.value.forEach(city => {
    const letter = city.letter
    if (!groups[letter]) {
      groups[letter] = []
    }
    groups[letter].push(city)
  })

  // 按字母排序
  const sortedGroups = Object.keys(groups)
    .sort()
    .reduce((acc, key) => {
      acc[key] = groups[key]
      return acc
    }, {})

  console.log('城市分组结果:', sortedGroups)
  return sortedGroups
})

// 添加切换城市面板的方法
const toggleCityPanel = () => {
  showCityPanel.value = !showCityPanel.value
}

// 添加点击外部关闭面板的处理
const handleClickOutside = (event) => {
  const citySelector = event.target.closest('.city-selector')
  if (!citySelector && showCityPanel.value) {
    showCityPanel.value = false
  }
}

// 添加生命周期钩子
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 修改返回实际定位城市的方法
const backToActualLocation = () => {
  const actualCity = localStorage.getItem('actualLocationCity')
  if (actualCity) {
    updateLocation(actualCity)
    // 更新选择的城市
    localStorage.setItem('selectedCity', actualCity)
    localStorage.setItem('cityTimestamp', Date.now().toString())
    showCityPanel.value = false
  }
}

// 添加更新实际定位城市的方法
const updateActualLocation = (city) => {
  actualLocationCity.value = city
}

</script>

<style scoped>
.header {
  width: 100%;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.center-section {
  flex: 1;
  display: flex;
  justify-content: center;
}

.right-section {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.top-nav {
  display: flex;
  gap: 40px;
}

.nav-link {
  font-size: 16px;
  color: #333;
  text-decoration: none;
  position: relative;
  padding: 0 5px;
  transition: color 0.3s ease;
}

.nav-link:hover {
  color: #ff5f16;
}

.nav-link.active {
  color: #ff5f16;
  font-weight: 500;
}

.nav-link.active::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #ff5f16;
}

.city-selector {
  position: relative;
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  margin-left: 20px;
  border-radius: 20px;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.city-selector:hover {
  background: #fff0e6;
}

.city-name {
  margin: 0 8px;
  font-size: 14px;
  color: #333;
}

.arrow-down {
  width: 8px;
  height: 8px;
  border: solid #666;
  border-width: 0 2px 2px 0;
  display: inline-block;
  padding: 2px;
  transform: rotate(45deg);
  transition: transform 0.3s ease;
}

.arrow-up {
  transform: rotate(-135deg);
}

.user-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 15px;
}

.btn-login,
.btn-register {
  padding: 8px 20px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
}

.btn-login {
  background: transparent;
  color: #333;
  border: 1px solid #e5e5e5;
}

.btn-login:hover {
  background: #f5f5f5;
  border-color: #d5d5d5;
}

.btn-register {
  background: #ff5f16;
  color: white;
}

.btn-register:hover {
  background: #ff7a3c;
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 15px;
  }

  .left-section, .center-section, .right-section {
    width: 100%;
    justify-content: center;
  }

  .top-nav {
    gap: 20px;
  }

  .user-actions {
    order: 2;
    margin-left: 0;
    width: 100%;
    justify-content: center;
  }

  .btn-login,
  .btn-register {
    padding: 6px 15px;
    font-size: 13px;
  }

  .top-nav {
    order: 3;
    width: 100%;
    justify-content: center;
  }
}

.user-profile {
  position: relative;
  cursor: pointer;
  margin-right: 20px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #ff5f16;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 10px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 8px 0;
  min-width: 160px;
  z-index: 1000;
}

.menu-item {
  padding: 10px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #333;
  transition: background-color 0.3s;
  cursor: pointer;
}

.menu-item:hover {
  background-color: #f5f5f5;
  color: #ff5f16;
}

.menu-divider {
  height: 1px;
  background-color: #eee;
  margin: 8px 0;
}

.iconfont {
  font-size: 16px;
}

.city-panel {
  position: absolute;
  top: calc(100% + 10px);
  left: 50%;
  transform: translateX(-50%);
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  padding: 24px;
  width: 480px;
  max-height: 600px;
  overflow-y: auto;
  z-index: 1000;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.city-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.city-group {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.letter {
  font-size: 16px;
  color: #ff5f16;
  padding: 0 0 12px 0;
  border-bottom: 2px solid #ff5f16;
  margin-bottom: 12px;
  font-weight: 600;
}

.cities {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 12px;
}

.city-item {
  text-align: center;
  padding: 10px 8px;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #eee;
  font-size: 14px;
  color: #333;
}

.city-item:hover {
  background: #fff0e6;
  color: #ff5f16;
  border-color: #ff5f16;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(255, 95, 22, 0.1);
}

/* 城市选择器样式 */
.city-selector {
  position: relative;
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  margin-left: 20px;
  border-radius: 20px;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.city-selector:hover {
  background: #fff0e6;
}

.city-name {
  margin: 0 8px;
  font-size: 14px;
  color: #333;
}

.arrow-down {
  width: 8px;
  height: 8px;
  border: solid #666;
  border-width: 0 2px 2px 0;
  display: inline-block;
  padding: 2px;
  transform: rotate(45deg);
  transition: transform 0.3s ease;
}

.arrow-up {
  transform: rotate(-135deg);
}

/* 自定义滚动条 */
.city-panel::-webkit-scrollbar {
  width: 6px;
}

.city-panel::-webkit-scrollbar-thumb {
  background: #ff5f16;
  border-radius: 3px;
}

.city-panel::-webkit-scrollbar-thumb:hover {
  background: #ff7a3c;
}

.city-panel::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 3px;
}

/* 添加响应式设计 */
@media (max-width: 768px) {
  .city-panel {
    width: 90vw;
    max-width: 480px;
    padding: 16px;
  }

  .cities {
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 8px;
  }

  .city-item {
    padding: 8px 4px;
    font-size: 13px;
  }

  .letter {
    font-size: 14px;
    padding-bottom: 8px;
  }
}

/* 添加定位图标样式 */
.icon-location {
  color: #ff5f16;
  font-size: 16px;
}

/* 热门城市样式 */
.hot-cities {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff0e6;
  border-radius: 8px;
}

.hot-cities .letter {
  color: #ff5f16;
  border-bottom-color: rgba(255, 95, 22, 0.3);
}

.hot-cities .city-item {
  background: white;
  border: 1px solid rgba(255, 95, 22, 0.2);
}

/* 添加加载动画 */
@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.loading {
  animation: pulse 1.5s infinite;
}

/* 添加城市项的焦点样式 */
.city-item:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(255, 95, 22, 0.3);
}

/* 添加无障碍支持 */
.city-item:focus-visible {
  outline: 2px solid #ff5f16;
  outline-offset: 2px;
}

/* 添加当前定位城市样式 */
.current-city {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.section-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.current-city-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #ff5f16;
  font-weight: 500;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.current-city-name:hover {
  background: #fff0e6;
}

.back-tip {
  font-size: 12px;
  color: #999;
  font-weight: normal;
}

.location-tip {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 8px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.3s;
  pointer-events: none;
}

.city-selector:hover .location-tip {
  opacity: 1;
}

/* 添加提示动画 */
@keyframes pulse {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

.back-tip {
  animation: pulse 2s infinite;
}
</style>